//
//  ZJChained.swift
//  Pods-ZJSwiftKit_Example
//
//  Created by 万孟超 on 2023/10/9.
//

import UIKit

/**
 * 通过ZJChained包装实现链式调用
 * 
 * Example
 *
 *       class ChainedClass: ZJChaniedProtocol {
 *          init() { }
 *          var propertyOne: String = ""
 *          var propertyTwo: Int = 0
 *       }
 *
 *       let chained = ChainedClass()
 *       chained.zjCn.propertyOne("propertyOne").propertyTwo("10")
 *
 *       // 消除结果未被使用警告可以用‘_’来代替返回值
 *       // _ = chained.zjCn
 *       //      .propertyOne("propertyOne")
 *       //      .propertyTwo(100)
 *
 *       //或者
 *
 *       //直接使用 ZJChained(ChainedClass())初始化，最后需要'.object'获取实例
 *       let chained = ZJChained(ChainedClass())
 *                          .propertyOne("propertyOne")
 *                          .propertyTwo(100)
 *                          .object
 *
 *       print(chained.propertyOne)
 *       print(chained.propertyTwo)
 *       // propertyOne
 *       // 100
 */
@dynamicMemberLookup
public struct ZJChained<ZJObject> {
    public let object: ZJObject
    
    /// 初始化包装器
    /// - Parameter object: 包装的实例
    public init(_ object: ZJObject) {
        self.object = object
    }
    
    /// 包装器通过KeyPath获取到属性
    /// 返回一个包装器自身，便于链式调用
    public subscript<Value>(dynamicMember keyPath: WritableKeyPath<ZJObject, Value>) -> ((Value) -> ZJChained<ZJObject>) {
        var subject = object
        return {
            subject[keyPath: keyPath] = $0
            return ZJChained(subject)
        }
    }
}

/// A type that has reactive extensions.
public protocol ZJChaniedProtocol { }

extension ZJChaniedProtocol {
    
    /// ZJPrefix extensions.
    public static var zjCn: ZJChained<Self>.Type {
        get{ ZJChained.self }
        set{ }
    }
    
    /// ZJPrefix extensions.
    public var zjCn: ZJChained<Self> {
        get{ ZJChained(self) }
        set {}
    }
}

extension NSObject: ZJChaniedProtocol { }



